package 中等;

public class 分割等和子集416 {
    public static void main(String[] args) {
        int[] nums = {1,5,11,5};
        System.out.println(canPartition2(nums));

    }

    public static boolean canPartition1(int[] nums) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if (sum%2 != 0){
            return false;
        }
        int len = nums.length;
        sum = sum / 2;
        boolean[][] dp = new boolean[len+1][sum+1];
        for (int i = 0; i < len+1; i++) {
            dp[i][0] = true;
        }
        for (int i = 1; i < len+1; i++) {

            for (int j = 1; j <= sum; j++) {
                //如果定义的容量不够装这个东西,就只能选择不装
                if (j - nums[i-1] < 0){
                    dp[i][j] = dp[i-1][j];
                } else {
                    dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i-1]];
                }

            }
        }
        return dp[len][sum];

    }

    public static boolean canPartition2(int[] nums) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if (sum%2 != 0){
            return false;
        }
        int len = nums.length;
        sum = sum / 2;
        //boolean[][] dp = new boolean[len+1][sum+1];
        boolean[] dp = new boolean[sum+1];
        dp[0] = true;
        for (int i = 1; i < len+1; i++) {
            for (int j = sum; j >= 1; j--) {
                //如果定义的容量不够装这个东西,就只能选择不装
                if (j - nums[i-1] >= 0){
                    dp[j] = dp[j] || dp[j-nums[i-1]];
                }

            }
        }
        return dp[sum];

    }
}
